package com.pxene.dmp.common;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public final class FEhcache
{
    public static final Integer DEFAULT_MAX_ELEMENTS = Integer.valueOf(1000000);
    public static final Long DEFAULT_LIVE_SECONDS = Long.valueOf(30L);
    public static final Long DEFAULT_IDLE_SECONDS = Long.valueOf(0L);
    private static final CacheManager cacheManager = CacheManager.create();
    private static final Logger LOGGER = LogManager.getLogger(FEhcache.class);

    public static final void setCacheContent(Cache _cache, String _key, Object _value)
            throws Exception
    {
        UFormat.checkEmptyParam("FEhcache", "setCacheContent", new Object[] { _cache, _key, _value });

        _cache.put(new Element(_key, _value));
    }

    public static final void setCacheContent(String _cacheName, String _key, Object _value)
            throws Exception
    {
        setCacheContent(cacheManager.getCache(_cacheName), _key, _value);
    }

    public static final Object getCacheContent(Cache _cache, String _key)
            throws Exception
    {
        UFormat.checkEmptyParam("FEhcache", "getCacheContent", new Object[] { _cache, _key });

        Element target = _cache.get(_key);
        return target == null ? null : target.getObjectValue();
    }

    public static final Object getCacheContent(String _cacheName, String _key)
            throws Exception
    {
        return getCacheContent(cacheManager.getCache(_cacheName), _key);
    }

    public static final synchronized Cache getMemCache(String _cacheName, Integer _maxElements, Long _liveSec, Long _idleSec)
            throws Exception
    {
        UFormat.checkEmptyParam("FEhcache", "getMemCache", new Object[] { _cacheName, _maxElements, _liveSec, _idleSec });
        if (cacheManager.cacheExists(_cacheName)) {
            return cacheManager.getCache(_cacheName);
        }
        Cache _target = new Cache(_cacheName, _maxElements.intValue(), false, false, _liveSec.longValue(), _idleSec.longValue());

        cacheManager.addCache(_target);

        LOGGER.debug(UFormat.buf2str(new String[] { "FEhcache : Succeed to initMemCache [ ", _target
                .getName(), " ]" }));
        return _target;
    }

    public static final Cache getMemCache(String _cacheName)
            throws Exception
    {
        return getMemCache(_cacheName, DEFAULT_MAX_ELEMENTS, DEFAULT_LIVE_SECONDS, DEFAULT_IDLE_SECONDS);
    }
}

